package com.metal.gear.certification.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.metal.gear.certification.entity.dto.depart.SysDepartSaveAndEditDto;
import com.metal.gear.certification.entity.po.SysDepart;
import com.metal.gear.certification.entity.po.SysUser;
import com.metal.gear.certification.entity.model.DepartIdModel;
import com.metal.gear.certification.entity.model.SysDepartTreeModel;
import com.metal.gear.certification.entity.vo.dept.SysDepartTreeVo;
import com.metal.gear.certification.service.ISysDepartService;

import com.metal.gear.certification.service.ISysUserDepartService;
import com.metal.gear.certification.service.ISysUserService;
import com.metal.gear.common.constant.CacheConstant;
import com.metal.gear.common.constant.CommonConstant;
import com.metal.gear.common.entity.Result;
import com.metal.gear.common.exception.SzlBusinessException;
import com.metal.gear.common.util.tree.SzlTreeUtil;
import io.swagger.annotations.Api;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.hateoas.MediaTypes;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;



import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * <p>
 *
 * @Author: lijiexi
 * @Since： 2019-01-22
 */
@Tag(name = "3.组织机构管理")
@RestController
@RequestMapping("/sys/sysDepart")
@Slf4j
public class SysDepartController {

    @Autowired
    private ISysDepartService sysDepartService;

    @Autowired
    private ISysUserService sysUserService;


    @Operation(summary = "查询完整的组织机构树")
    @ApiOperationSupport(order = 1)
    @GetMapping(value = "/queryTreeList",produces = {MediaType.APPLICATION_JSON_VALUE})
    public Result<List<SysDepartTreeVo>> queryTreeList(HttpServletResponse response) {
        return Result.ok(
                SzlTreeUtil.build(
                        sysDepartService.list().stream()
                                .map(SysDepartTreeVo::convertFrom)
                                .collect(Collectors.toList())
                )
        );
    }


    @Operation(summary =  "获取某个部门的所有父级部门的ID", description =  "获取某个部门的所有父级部门的ID")
    @ApiOperationSupport(order = 2)
    @GetMapping(value = "/queryAllParentIdById",produces = {MediaType.APPLICATION_JSON_VALUE})
    public Result<List<String>> queryParentIdsById(@RequestParam String departId) {
        return Result.ok(sysDepartService.listAllParentIdByDepartId(departId));
    }

    @Operation(summary =  "获取某个部门的所有父级部门的ID", description =  "获取某个部门的所有父级部门的ID")
    @ApiOperationSupport(order = 3)
    @GetMapping(value = "/queryAllParentIdByOrgCode",produces = {MediaType.APPLICATION_JSON_VALUE})
    public Result<List<String>> queryParentIdsByOrgCode(@RequestParam String orgCode) {
        return Result.ok(sysDepartService.listAllParentIdByOrgCode(orgCode));
    }


    @Operation(summary =  "组织机构Id树型列表", description =  "查询数据,添加或编辑页面对该方法发起请求,以树结构形式加载所有部门的名称,方便用户的操作")
    @ApiOperationSupport(order = 3)
    @GetMapping(value = "/queryIdTree",produces = {MediaType.APPLICATION_JSON_VALUE})
    public Result<List<DepartIdModel>> queryIdTree() {
        return Result.ok(sysDepartService.queryDepartIdTreeList());
    }

    @Operation(summary =  "部门详情",description =  "")
    @ApiOperationSupport(order = 3)
    @GetMapping(value = "/detail",produces = {MediaType.APPLICATION_JSON_VALUE})
    public Result<SysDepart> listAll(@RequestParam String departId) {
       return Result.ok(sysDepartService.getById(departId));
    }

    @Operation(summary =  "新建部门", description =  "添加新数据,添加用户新建的组织机构对象数据并保存到数据库")
    @ApiOperationSupport(order = 3)
    @PostMapping(value =  "/add",produces = {MediaType.APPLICATION_JSON_VALUE})
    @CacheEvict(value = {CacheConstant.SYS_DEPARTS_CACHE, CacheConstant.SYS_DEPART_IDS_CACHE}, allEntries = true)
    public Result<Boolean> add(@RequestBody SysDepartSaveAndEditDto saveAndEditDto) {
//        SysDepart sysDepart = SysDepartSaveAndEditDto.transformTo(saveAndEditDto);
//        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
//        String username = loginUser.getUsername();
//        try {
//            sysDepart.setCreateBy(username);
//            sysDepartService.saveDepartData(sysDepart, username);
//            return Result.ok("添加成功！");
//        } catch (Exception e) {
//            throw new SzlBusinessException("操作失败", e);
//        }
        return Result.ok();
    }


    @Operation(summary =  "更新部门", description =  "编辑数据,编辑部门的组织机构数据并保存到数据库")
    @ApiOperationSupport(order = 3)
    @PutMapping(value = "/edit",produces = {MediaType.APPLICATION_JSON_VALUE})
    @CacheEvict(value = {CacheConstant.SYS_DEPARTS_CACHE, CacheConstant.SYS_DEPART_IDS_CACHE}, allEntries = true)
    public Result<Boolean> edit(@RequestBody SysDepart sysDepart, HttpServletRequest request) {
//        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
//        String username = loginUser.getUsername();
//        sysDepart.setUpdateBy(username);
//        SysDepart sysDepartEntity = sysDepartService.getById(sysDepart.getId());
//        if (sysDepartEntity == null) {
//            return Result.error("未找到对应实体");
//        } else {
//            return Result.ok("修改成功!", sysDepartService.updateDepartDataById(sysDepart, username));
//        }
        return Result.ok();
    }

    @Operation(summary =  "删除部门", description =  "通过id删除，删除部门")
    @ApiOperationSupport(order = 3)
    @DeleteMapping(value = "/delete",produces = {MediaType.APPLICATION_JSON_VALUE})
    @CacheEvict(value = {CacheConstant.SYS_DEPARTS_CACHE, CacheConstant.SYS_DEPART_IDS_CACHE}, allEntries = true)
    public Result<Boolean> delete(@RequestParam String id) {
        SysDepart sysDepart = sysDepartService.getById(id);
        if (sysDepart == null) {
            return Result.error("未找到对应实体");
        } else {
            return Result.ok(sysDepartService.deleteDepart(id));
        }
    }

    @Operation(summary =  "批量删除", description =  "批量删除，根据前端请求的多个ID，对数据库执行删除相关部门数据的操作")
    @ApiOperationSupport(order = 3)
    @DeleteMapping(value = "/deleteBatch",produces = {MediaType.APPLICATION_JSON_VALUE})
    @CacheEvict(value = {CacheConstant.SYS_DEPARTS_CACHE, CacheConstant.SYS_DEPART_IDS_CACHE}, allEntries = true)
    public Result<SysDepart> deleteBatch(@RequestParam String ids) {
        if (ids == null || "".equals(ids.trim())) {
            return Result.error("参数不识别！");
        } else {
            this.sysDepartService.deleteBatchWithChildren(Arrays.asList(ids.split(",")));
            return Result.ok("删除成功!");
        }
    }


    @Operation(summary = "部门搜索功能方法,根据关键字模糊搜索相关部门")
    @ApiOperationSupport(order = 3)
    @GetMapping(value =  "/searchBy",produces = {MediaType.APPLICATION_JSON_VALUE})
    public Result<List<SysDepartTreeModel>> searchBy(@RequestParam(name = "keyWord") String keyWord, @RequestParam(name = "myDeptSearch", required = false) String myDeptSearch) {
//        Result<List<SysDepartTreeModel>> result = new Result<>();
//        //部门查询，myDeptSearch为1时为我的部门查询，登录用户为上级时查只查负责部门下数据
//        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
//        String departIds = null;
//        if (oConvertUtils.isNotEmpty(user.getUserIdentity()) && user.getUserIdentity().equals(CommonConstant.USER_IDENTITY_2)) {
//            departIds = user.getDepartIds();
//        }
//        List<SysDepartTreeModel> treeList = this.sysDepartService.searchByKeyWord(keyWord, myDeptSearch, departIds);
//        if (treeList == null || treeList.size() == 0) {
//            result.setSuccess(false);
//            result.setMessage("未查询匹配数据！");
//            return result;
//        }
//        result.setResult(treeList);
//        return result;
        return Result.ok();
    }


    @Operation(summary = "导出ExcelProperty数据")
    @ApiOperationSupport(order = 3)
    @GetMapping(value =  "/exportXls",produces = {MediaType.APPLICATION_JSON_VALUE})
    public ModelAndView exportXls(SysDepart sysDepart, HttpServletRequest request) {
      throw new SzlBusinessException("接口未实现");
    }

    @Operation(summary = "导入ExcelProperty数据")
    @ApiOperationSupport(order = 3)
    @PostMapping(value = "/importExcelProperty",produces = {MediaType.APPLICATION_JSON_VALUE})
    public Result<Boolean> importExcelProperty(HttpServletRequest request, HttpServletResponse response) {
        throw new SzlBusinessException("接口未实现");
    }




    /**
     * 查询数据 查出所有部门,并以树结构数据格式响应给前端
     *
     * @return
     */
    @Operation(summary = "查询数据 查出所有部门,并以树结构数据格式响应给前端")
    @ApiOperationSupport(order = 3)
    @GetMapping(value = "/queryTreeByKeyWord",produces = {MediaType.APPLICATION_JSON_VALUE})
    public Result<Map<String, Object>> queryTreeByKeyWord(@RequestParam(name = "keyWord", required = false) String keyWord) {
        Result<Map<String, Object>> result = new Result<>();
        try {
            Map<String, Object> map = new HashMap(5);
            List<SysDepartTreeModel> list = sysDepartService.queryTreeByKeyWord(keyWord);
            //根据keyWord获取用户信息
            LambdaQueryWrapper<SysUser> queryUser = new LambdaQueryWrapper<>();
            queryUser.eq(SysUser::getDelFlag, CommonConstant.DEL_FLAG_0);
            queryUser.and(i -> i.like(SysUser::getUsername, keyWord).or().like(SysUser::getRealname, keyWord));
            List<SysUser> sysUsers = this.sysUserService.list(queryUser);
            map.put("userList", sysUsers);
            map.put("departList", list);
            result.setResult(map);
            result.setSuccess(true);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return result;
    }


}
